package com.wu.framework.oauth.servie;

import com.wu.framework.upms.api.UpmsApi;
import com.wu.framework.upms.domain.entity.UcUser;
import com.wu.framework.util.SecurityContextUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Collections;

/**
 * description
 *
 * @author 吴佳伟
 * @date 2021/5/25 2:59 下午
 */
@Service
public class Oauth2UserDetailsService implements UserDetailsService {

    private final UpmsApi upmsApi;

    public Oauth2UserDetailsService(UpmsApi upmsApi) {
        this.upmsApi = upmsApi;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        String currentUserTenantId = SecurityContextUtils.getCurrentUserTenantId();
        if (ObjectUtils.isEmpty(currentUserTenantId))throw new IllegalArgumentException("请求头中必须包含租户ID");
        UcUser ucUserByTenantIdAndUserName = upmsApi.getUcUserByTenantIdAndUserName(currentUserTenantId, username);
        if(ObjectUtils.isEmpty(ucUserByTenantIdAndUserName)) throw new UsernameNotFoundException("用户不存在");
        return new User(ucUserByTenantIdAndUserName.getUserName(), ucUserByTenantIdAndUserName.getPassword(),
                Collections.emptyList());
    }

}
